package google.sites.model.commands;

import com.google.gdata.client.sites.SitesService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.XhtmlTextConstruct;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.data.sites.BaseContentEntry;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.XmlBlob;
import dev.tools.design.patterns.command.Command;
import google.sites.model.Model;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 04-10-2013
 * Time: 15:05
 */
public abstract class SitesCommand extends Command {

    protected SitesService getService(){
        return Model.INSTANCE.service;
    }

    protected void setContentBlob(BaseContentEntry<?> entry) {
        XmlBlob xml = new XmlBlob();
        xml.setBlob(String.format(
                "content for %s", entry.getCategories().iterator().next().getLabel()));
        entry.setContent(new XhtmlTextConstruct(xml));
    }

    public String getContentFeedUrl() {
        return Model.INSTANCE.getContentFeedUrl();
    }

    public String getRevisionFeedUrl() {
        return Model.INSTANCE.getRevisionFeedUrl();
    }

    public String getActivityFeedUrl() {
        return Model.INSTANCE.getActivityFeedUrl();
    }

    public String getSiteFeedUrl() {
        return Model.INSTANCE.getSiteFeedUrl();
    }

    public String getAclFeedUrl(String siteName) {
        return Model.INSTANCE.getAclFeedUrl(siteName);
    }

    /**
     * Downloads a file from the specified URL to disk.
     *
     * @param downloadUrl  The full URL to download the file from.
     * @param fullFilePath The local path to save the file to on disk.
     * @throws com.google.gdata.util.ServiceException
     *
     * @throws java.io.IOException
     */
    protected void downloadFile(String downloadUrl, String fullFilePath) throws IOException,
            ServiceException {
        System.out.println("Downloading file from: " + downloadUrl);

        MediaContent mc = new MediaContent();
        mc.setUri(downloadUrl);
        MediaSource ms = getService().getMedia(mc);

        InputStream inStream = null;
        FileOutputStream outStream = null;

        try {
            inStream = ms.getInputStream();
            outStream = new FileOutputStream(fullFilePath);

            int c;
            while ((c = inStream.read()) != -1) {
                outStream.write(c);
            }
        } finally {
            if (inStream != null) {
                inStream.close();
            }
            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        }
    }
}
